package com.xbsg.protocol.xf.test;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @功能描述 TCP连接
 * @创建时间 2020/10/20 9:52
 **/
@Slf4j
public class MyThread extends Thread {
    private String ip;
    private int port;

    public static final char END_CHAR = '\n';

    public MyThread(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    @Override
    public void run() {
        while (true) {
            try {
                String msg = "";
                //TCP发送数据
                //String result = sendAndReceive(this.ip, this.port, msg);
                //打印响应的数据
                String result = receiveData(this.ip, this.port);
                log.info("返回内容:" + result);
                //Map map = dealData(result);
                //log.info(map.toString());

                //间隔60秒发送一次
//                int time = 60 * 1000;
//                try {
//                    Thread.sleep(time);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static Map dealData(String msg) {
        //数据转换成需要的内容
        Map map = new HashMap<String, String>();
        return map;
    }

    private static String receiveData(String ip, int port){
        InputStream in = null;        //读
        String respData = null;       //响应报文
        Socket socket = new Socket(); //客户机

        try {

            socket.setTcpNoDelay(true);
            socket.setReuseAddress(true);
            socket.setSoTimeout(30000);
            socket.setSoLinger(true, 5);
            socket.setSendBufferSize(1024);
            socket.setReceiveBufferSize(1024);
            socket.setKeepAlive(true);
            socket.connect(new InetSocketAddress(ip, port), 30000);

            in = socket.getInputStream();
            //从输入流中解析数据，输入流来自服务端的响应
            in = socket.getInputStream();
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[512];
            int len = -1;
            while ((len = in.read(buffer)) != -1) {
                bytesOut.write(buffer, 0, len);
            }
            respData = bytesOut.toString();

        } catch (Exception e) {
            log.error("TCP连接失败：", e);
            e.printStackTrace();
        } finally {
            if (null != socket && socket.isConnected() && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("关闭客户机Socket时发生异常,堆栈信息如下");
                    e.printStackTrace();
                }
            }
        }
        return respData;
    }

    private static String sendAndReceive(String ip, int port, String msg) {
        //这里比较重要，需要给请求信息添加终止符，否则服务端会在解析数据时，一直等待
        msg = msg + END_CHAR;
        StringBuilder receiveMsg = new StringBuilder();
        //开启一个链接，需要指定地址和端口
        OutputStream out = null;      //写
        InputStream in = null;        //读
        String respData = null;       //响应报文
        Socket socket = new Socket(); //客户机

        try {
            socket.setTcpNoDelay(true);
            socket.setReuseAddress(true);
            socket.setSoTimeout(30000);
            socket.setSoLinger(true, 5);
            socket.setSendBufferSize(1024);
            socket.setReceiveBufferSize(1024);
            socket.setKeepAlive(true);
            socket.connect(new InetSocketAddress(ip, port), 30000);
//            Socket client = new Socket(ip, port);
            //向输出流中写入数据，传向服务端
            out = socket.getOutputStream();
            out.write(msg.getBytes());

            //从输入流中解析数据，输入流来自服务端的响应
            in = socket.getInputStream();
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[512];
            int len = -1;
            while ((len = in.read(buffer)) != -1) {
                bytesOut.write(buffer, 0, len);
            }
            respData = bytesOut.toString();
        } catch (Exception e) {
            log.error("TCP连接失败：", e);
            e.printStackTrace();
        } finally {
            if (null != socket && socket.isConnected() && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("关闭客户机Socket时发生异常,堆栈信息如下");
                    e.printStackTrace();
                }
            }
        }
        return respData;
    }
}
